<template>
	<div class="top">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">课程管理</a>
			</el-breadcrumb-item>
			<el-breadcrumb-item>
				<a href="/Classification">订单管理</a>
			</el-breadcrumb-item>
		</el-breadcrumb>
	</div>

	<div class="middel">
		<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
			<el-form-item label="学员昵称">
				<el-input v-model="queryInfo.username" placeholder="请输入学员昵称" clearable />
			</el-form-item>
			<el-form-item label="课程名称">
				<el-input v-model="queryInfo.courseName" placeholder="请输入课程名称" clearable />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="search">搜索</el-button>
			</el-form-item>
		
			<el-form-item>
<!--				<el-button type="danger" @click="batchDelete" :disabled="multipleSelection.length === 0">-->
<!--					批量删除-->
<!--				</el-button>-->
			</el-form-item>
		</el-form>
	</div>

	<div class="content">
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :loading="loading"
      border
      stripe
      class="category-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="订单ID" width="100" align="center" />
      <el-table-column prop="username" label="学员昵称" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="courseName" label="课程名称" min-width="180" align="center" show-overflow-tooltip />
      <el-table-column prop="orderTime" label="下单时间" min-width="180" align="center" show-overflow-tooltip />

      <!-- 新增：实付金额列 -->
      <el-table-column prop="orderPrice" label="实付金额" min-width="120" align="center">
        <template #default="scope">
          <!-- 格式化金额为两位小数 + 单位 -->
          {{ scope.row.orderPrice !== undefined ? scope.row.orderPrice.toFixed(2) + ' 元' : '0.00 元' }}
        </template>
      </el-table-column>

      <!-- 新增：订单状态列（转换数字为文字） -->
      <el-table-column label="订单状态" min-width="120" align="center">
        <template #default="scope">
          <el-tag
            :type="getStatusType(scope.row.orderType)"
            size="small"
          >
            {{ getStatusText(scope.row.orderType) }}
          </el-tag>
        </template>
      </el-table-column>

<!--      <el-table-column label="操作" width="240" align="center">-->
<!--        &lt;!&ndash; 原有操作按钮 &ndash;&gt;-->
<!--      </el-table-column>-->
    </el-table>

		<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="queryInfo.pageNum"
			:page-sizes="[5, 10, 15, 20]"
			:page-size="queryInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			style="margin-top: 20px"
		/>
	</div>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
		<el-form :model="form" label-width="110px" class="dialog-form">
			<el-form-item label="学员昵称" required>
				<el-input v-model="form.nickname" autocomplete="off" maxlength="30" show-word-limit />
			</el-form-item>
			<el-form-item label="课程名称" required>
				<el-input v-model="form.courseName" autocomplete="off" maxlength="50" show-word-limit />
			</el-form-item>
			<el-form-item label="下单时间" required>
				<el-input v-model="form.orderTime" autocomplete="off" maxlength="30" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus';

// 查询参数
const queryInfo = reactive({
	id: '',
  username: '',
	courseName: '',
	pageSize: 10,
	pageNum: 1
});
const getStatusText = (orderType: number | undefined) => {
  if (orderType === undefined) return '未知状态';
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '待评价',
    3: '已评价'
  };
  return statusMap[orderType] || '未知状态';
};

// 订单状态标签样式映射（与 Element Plus 标签 type 对应）
const getStatusType = (orderType: number | undefined) => {
  if (orderType === undefined) return 'default';
  const typeMap = {
    0: 'info',      // 蓝色（未支付）
    1: 'success',   // 绿色（已支付）
    2: 'warning',   // 黄色（待评价）
    3: 'primary'    // 紫色（已评价）
  };
  return typeMap[orderType] || 'default';
};

// 表格数据和分页
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 选择相关
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);

const axios = getCurrentInstance().appContext.config.globalProperties.axios;

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref('新增订单');
const form = reactive({
	id: '',
	nickname: '',
	courseName: '',
	orderTime: ''
});
let dialogMode = 'add';

// 查询列表
const queryDataList = () => {
	loading.value = true;
	axios.get('/courseOrder/all', {
		params: queryInfo
	})
	.then((response) => {
		if (response && response.code === 200) {
			tableData.value = response.data.list || [];
			total.value = response.data.total || 0;
      console.log(tableData.value);
		} else {
			ElMessage.error(response.message || '查询失败');
		}
	})
	.catch(() => {
		ElMessage.error('网络请求错误，请检查网络连接或服务器状态');
	})
	.finally(() => {
		loading.value = false;
	});
};

onMounted(() => {
	queryDataList();
});

// 搜索
const search = () => {
	queryInfo.pageNum = 1;
	queryDataList();
};

// 分页
const handleSizeChange = (size: number) => {
	queryInfo.pageSize = size;
	queryDataList();
};
const handleCurrentChange = (num: number) => {
	queryInfo.pageNum = num;
	queryDataList();
};

// 选择
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};

// 打开弹窗
function openDialog(mode: 'add' | 'edit', row?: any) {
	dialogMode = mode;
	if (mode === 'add') {
		dialogTitle.value = '新增订单';
		form.id = '';
		form.nickname = '';
		form.courseName = '';
		form.orderTime = '';
	} else if (mode === 'edit' && row) {
		dialogTitle.value = '编辑订单';
		form.id = row.id;
		form.nickname = row.nickname;
		form.courseName = row.courseName;
		form.orderTime = row.orderTime;
	}
	dialogVisible.value = true;
}

// 新增/编辑提交
function submitForm() {
	if (!form.nickname.trim()) {
		ElMessage.warning('请输入学员昵称');
		return;
	}
	if (!form.courseName.trim()) {
		ElMessage.warning('请输入课程名称');
		return;
	}
	if (!form.orderTime) {
		ElMessage.warning('请输入下单时间');
		return;
	}
	if (dialogMode === 'add') {
		axios.post('courseOrder', {
			nickname: form.nickname,
			courseName: form.courseName,
			orderTime: form.orderTime
		}).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('新增成功');
				dialogVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error(resp.message || '新增失败');
			}
		});
	} else if (dialogMode === 'edit') {
		axios.put('courseOrder', {
			id: form.id,
			nickname: form.nickname,
			courseName: form.courseName,
			orderTime: form.orderTime
		}).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('编辑成功');
				dialogVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error(resp.message || '编辑失败');
			}
		});
	}
}

// 删除
function deleteOrder(id: number) {
	ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
		type: 'warning'
	}).then(() => {
		axios.delete(`courseOrder/${id}`).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('删除成功');
				queryDataList();
			} else {
				ElMessage.error(resp.message || '删除失败');
			}
		});
	});
}

// 批量删除
function batchDelete() {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择要删除的订单');
		return;
	}
	ElMessageBox.confirm('确定要批量删除选中的订单吗？', '提示', {
		type: 'warning'
	}).then(() => {
		const ids = multipleSelection.value.map((item: any) => item.id);
		axios.delete('courseOrder/batch', { data: { ids } }).then((resp: any) => {
			if (resp.code === 200) {
				ElMessage.success('批量删除成功');
				queryDataList();
			} else {
				ElMessage.error(resp.message || '批量删除失败');
			}
		});
	});
}
</script>

<style scoped>
.top {
	background-color: #f8f9fa;
	padding: 12px 20px;
	margin-bottom: 15px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.el-breadcrumb {
	max-width: 1200px;
	margin: 0 auto;
}
.middel {
	background: #fff;
	padding: 20px;
	margin-bottom: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.demo-form-inline {
	display: flex;
	align-items: center;
	gap: 15px;
}
.demo-form-inline .el-form-item {
	margin-right: 20px;
}
.demo-form-inline .el-input,
.demo-form-inline .el-select {
	width: 220px;
}
.el-button {
	min-width: 100px;
}
.el-button + .el-button {
	margin-left: 10px;
}
.content {
	background: #fff;
	padding: 20px;
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.category-table {
	background: #fff;
	border-radius: 8px;
}
.el-table {
	margin-bottom: 20px;
}
.el-table__header-wrapper {
	border-radius: 6px 6px 0 0;
}
.el-table__body-wrapper {
	border-radius: 0 0 6px 6px;
}
.el-pagination {
	display: flex;
	justify-content: flex-end;
	margin-top: 30px !important;
}
.dialog-form {
	padding-top: 10px;
}
</style>